<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\shop\Goods;
use app\common\utils\Utils;
use fast\Random;
use app\common\model\shop\Order as OrderModel;
use think\Db;
use Yansongda\Pay\Pay;

/**
 * 会员接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['add'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 我卖出
     */
    public function sale() {

    }


    public function pay() {
        //创建订单   ==》 支付参数，键为goods_id 值为数量
        $goods_ids = input('goods_ids/a', []);
        $params = $this->request->param();

        if (!$goods_ids) {
            $this->error('请选择购买的商品');
        }
        $type = input('type/s', '');
        if (!in_array($type, ['aliApp', 'wxApp'])) {
            $this->error('支付类型错误');
        }

        $order_sn = Random::uuid(); //订单号
        $amount = 0;
        $order_goods = [];
        foreach ($goods_ids as $k => $v) {
            if ($v <= 0) {
                $this->error('商品数量不能小于等于0');
            }
            $good = Goods::get($k);
            if (!$good) {
                $this->error('商品ID错误');
            }
            $temp = [
                'goods_id'=> $good['id'],
                'num' => $v,
                'price' => $good['price']
            ];
            array_push($order_goods, $temp);
            $allPrice = Utils::processMoney($v, $good['price'], '*');
            $amount = Utils::processMoney($amount, $allPrice, '+');
        }

        $order = [
            'user_id' => UID,
            'order_no' => $order_sn,
            'amount' => $amount,
        ];
        unset($params['goods_ids']);
        $order = array_merge($params, $order);
        $paystring = '';
        Db::startTrans();
        try {
            (new \app\common\validate\shop\Order())->goCheck(null, $order);
            $res = OrderModel::create($order);

            foreach ($order_goods as $k => &$v) {
                $v['order_id'] = $res['id'];
            }

            Db::name('shop_order_goods')->insertAll($order_goods);

            //生成支付订单
            $paystring = $this->toPay($type, $order_sn, $amount);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('创建订单失败');
        }

        $this->success('创建订单成功', $paystring);
    }


    private function toPay($type, $order_sn, $amount) {
        $res = '';
        $config = config('pay_config');
        switch ($type) {
            case 'aliApp':
                $order = [
                    'out_trade_no' => $order_sn,
                    'total_amount' => $amount,
                    'subject'      => '购买商品',
                ];
                $res = Pay::alipay($config['ali'])->app($order);

                break;
            case 'wxApp':
                $order = [
                    'out_trade_no' => $order_sn,
                    'total_fee' => $amount * 100,
                    'body' => 'vip包月',
                ];

                $res = Pay::wechat($config['wx'])->app($order);
                break;
            default:
                $this->error('支付类型错误');
        }


        if (!$res) {
            $this->error('支付出现错误');
        }


        return $res->getContent();
    }




    
}
